package com.github.baichuan.web.reactive;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.InetAddress;

@Slf4j
public class ClientIP {

    public static String get(ServerHttpRequest request){
        String ip = request.getHeaders().getFirst("x-forwarded-for");
        if(invalid(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
            log.debug("Proxy-Client-IP={}", ip);
        }
        if(invalid(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
            log.debug("WL-Proxy-Client-IP={}", ip);
        }
        if(invalid(ip)) {
            ip = request.getRemoteAddress().getHostName();
            if (ip.equals ("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                try {
                    InetAddress inet = InetAddress.getLocalHost ();
                    ip = inet.getHostAddress();
                    log.debug("网卡取本机配置的IP={}", ip);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        log.debug("ip={}", ip);
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length () > 15 && ip.indexOf (",") > 0) {
            ip = ip.substring (0, ip.indexOf (","));
        }
        return ip;
    }

    private static boolean invalid(String ip){
        return StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase (ip);
    }
}
